<template>
  <div class="record-container">
    <!-- 搜索和分页控件 -->
    <div class="searchBox">
      <el-form :inline="true" :model="queryParams" class="demoFormInline">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="企业名称">
          <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" />
        </el-form-item>
        <!-- <el-form-item label="部门">
          <el-select
            v-model="queryParams.department"
            placeholder="请选择部门"
            style="width: 120px"
            clearable
          >
            <el-option
              v-for="(dept, index) in departmentList"
              :key="index"
              :label="dept"
              :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招商员">
          <el-select
            v-model="queryParams.investmentStaff"
            placeholder="请选择招商员"
            style="width: 120px"
            clearable
          >
            <el-option
              v-for="(dept, index) in responsiblePersonList"
              :key="index"
              :label="dept"
              :value="dept"
            />
          </el-select>
        </el-form-item> -->
         <el-form-item label="部门">
          <el-select
            v-model="queryParams.department"
            placeholder="请选择部门"
            style="width: 159px"
            multiple
            filterable
            remote
            :remote-method="filterDepartments"
            :loading="departmentLoading"
            reserve-keyword
          >
            <el-option
              v-for="(visitor, index) in filteredDepartmentList"
              :key="index"
              :label="visitor"
              :value="visitor"
            />
          </el-select>
        </el-form-item>
         <el-form-item label="招商员">
          <el-select
            v-model="queryParams.investmentStaff"
            placeholder="请选择招商员"
            style="width: 159px"
            multiple
            filterable
            remote
            :remote-method="filterInvestmentStaffs"
            :loading="investmentStaffLoading"
            reserve-keyword
          >
            <el-option
              v-for="(visitor, index) in filteredInvestmentStaffList"
              :key="index"
              :label="visitor"
              :value="visitor"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进方式">
          <el-select
            v-model="queryParams.followMethod"
            placeholder="请选择跟进方式"
            style="width: 150px"
            clearable
          >
            <el-option label="上门拜访" value="上门拜访" />
            <el-option label="来访接待" value="来访接待" />
            <el-option label="园内走访" value="园内走访" />
            <el-option label="电话拜访" value="电话拜访" />
            <el-option label="微信QQ联系" value="微信QQ联系" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户类型">
          <el-cascader
            v-model="queryParams.investmentTargetValue"
            :options="customerTypeOptions"
            :props="cascaderProps"
            placeholder="请选择客户类型"
            style="width: 200px"
            clearable
            collapse-tags
            @change="handleCustomerTypeChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="陪访人员">
          <el-select
            v-model="queryParams.accompanyStaff"
            placeholder="请选择陪访人员"
            style="width: 150px"
            multiple
            filterable
            remote
            :remote-method="filterAccompanyingVisitors"
            :loading="accompanyingVisitorLoading"
            reserve-keyword
          >
            <el-option
              v-for="(visitor, index) in filteredAccompanyingVisitorList"
              :key="index"
              :label="visitor"
              :value="visitor"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
          <el-button icon="Refresh" @click="resetForm">重置</el-button>
          <el-button icon="Plus" type="success" @click="handleAddFollowUp">添加跟进记录</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="tableContainer">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="department" label="项目" min-width="120" />
        <el-table-column prop="investmentStaff" label="招商员" min-width="100" />
        <el-table-column prop="accompanyStaff" label="陪访人员" min-width="100" />
        <el-table-column
          prop="companyName"
          label="企业名称"
          width="300"
          show-overflow-tooltip
        />
        <el-table-column prop="investmentTarget" label="客户类型" min-width="120" />
          <el-table-column prop="category" label="渠道分类" min-width="100"/>
        <el-table-column
          prop="followUpTime"
          label="跟进时间"
          min-width="120"
          width="200px"
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.followUpTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="followUpType" label="跟进方式" min-width="100">
          <template #default="scope">
            <el-tag 
              :type="getFollowUpTypeTagType(scope.row.followUpType)"
              disable-transitions
            >
              {{ scope.row.followUpType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="followUpContent"
          label="跟进内容"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="followUpCount" label="总跟进次数" min-width="100" />
        <el-table-column prop="customerSource" label="客户来源" min-width="120" />
        <el-table-column prop="customerProgress" label="客户进度" min-width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" @click="viewCompanyDetail(scope.row)"
                >查看</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="fetchData"
    />

    <!-- 抽屉组件 -->
    <CompanyDetailDrawer
      v-model="drawerVisible"
      :detail="selectedRow"
      :related-follow-list="[]"
      @view-follow="handleViewFollow"
    />

    <!-- 新增跟进记录 -->
    <el-dialog
      v-model="dialogAddFollowUpVisible"
      title="新增跟进记录"
      width="600px"
      :before-close="handleCloseFollowUp"
    >
      <el-form
        ref="formRefFollowUp"
        :model="formDataAddFollow"
        :rules="addFollowRecodeRules"
        label-width="120px"
        class="info-form"
      >
        <!-- 目标客户 -->
        <el-form-item label="目标客户" prop="companyName">
          <el-select
            v-model="formDataAddFollow.companyName"
            placeholder="请选择目标客户"
            style="width: 100%"
            filterable
            @change="handleProjectChange"
          >
            <el-option
              v-for="project in projectList"
              :key="project.customerCode"
              :label="project.companyName"
              :value="project.companyName"
            />
          </el-select>
        </el-form-item>

        <!-- 陪访人员 -->
       <el-form-item label="陪访人员">
          <el-select
            v-model="formDataAddFollow.accompanyStaff"
            placeholder="请选择"
            style="width: 100%"
            multiple
            filterable
            remote
            :remote-method="filterAccompanyingVisitors"
            :loading="accompanyingVisitorLoading"
            reserve-keyword
          >
            <el-option
              v-for="(visitor, index) in filteredAccompanyingVisitorList"
              :key="index"
              :label="visitor"
              :value="visitor"
            />
          </el-select>
        </el-form-item>

        <!-- 招商对象企业 -->
        <!-- <el-form-item label="招商对象企业" prop="targetEnterprise">
          <el-select
            v-model="formDataAddFollow.investmentTarget"
            placeholder="请选择"
            style="width: 40%"
          >
            <el-option label="企业" value="企业" />
            <el-option label="项目" value="项目" />
            <el-option label="机构" value="机构" />
          </el-select>
        </el-form-item> -->

        <!-- 联系人 -->
        <el-form-item label="联系人" prop="contactPerson">
          <el-select
            v-model="formDataAddFollow.contactPerson"
            placeholder="请选择"
            style="width: 85%"
          >
            <el-option
              v-for="(dept, index) in AddFollowContactList"
              :key="index"
              :label="dept"
              :value="dept"
            />
          </el-select>
          <el-button
            type="primary"
            icon="Plus"
            size="small"
            style="margin-left: 8px"
            @click="openAddContactForm"
          ></el-button>
        </el-form-item>

        <!-- 跟进方式 -->
        <el-form-item label="跟进方式" prop="followUpType">
          <el-select
            v-model="formDataAddFollow.followUpType"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="上门拜访" value="上门拜访" />
            <el-option label="来访接待" value="来访接待" />
            <el-option label="园内走访" value="园内走访" />
            <el-option label="电话拜访" value="电话拜访" />
            <el-option label="QQ微信联系" value="QQ微信联系" />
          </el-select>
        </el-form-item>

        <!-- 客户意向等级 -->
        <el-form-item label="客户意向等级" prop="customerIntentionLevel">
          <el-select
            v-model="formDataAddFollow.customerIntentionLevel"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="A级 (已缴纳意向金)" value="A级 (已缴纳意向金)" />
            <el-option label="B级 (1个月内可签约)" value="B级 (1个月内可签约)" />
            <el-option label="C级 (3个月内需持续培育)" value="C级 (3个月内需持续培育)" />
            <el-option label="D级 (明确表示无意向)" value="D级 (明确表示无意向)" />
          </el-select>
        </el-form-item>

<!--        &lt;!&ndash; 招商对象 :企业 政府部门 中介 第三方公司 同行载体&ndash;&gt;-->
<!--        <el-form-item label="客户类型" prop="investmentTarget">-->
<!--          <el-select-->
<!--            v-model="formDataAddFollow.investmentTarget"-->
<!--            placeholder="请选择"-->
<!--            style="width: 100%"-->
<!--          >-->
<!--            <el-option label="企业" value="企业" />-->
<!--            <el-option label="政府部门" value="政府部门" />-->
<!--            <el-option label="中介" value="中介" />-->
<!--            <el-option label="第三方公司" value="第三方公司" />-->
<!--            <el-option label="同行载体" value="同行载体" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <!-- 招商阶段：线上沟通询问，初次线下接触，二次及以上拜访，首次带看，二次及以上带看，商谈合同要素，定金缴纳 -->
        <el-form-item label="招商阶段" prop="customerProgress">
          <el-select
            v-model="formDataAddFollow.customerProgress"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="线上沟通询问" value="线上沟通询问" />
            <el-option label="初次线下接触" value="初次线下接触" />
            <el-option label="二次及以上拜访" value="二次及以上拜访" />
            <el-option label="首次带看" value="首次带看" />
            <el-option label="二次及以上带看" value="二次及以上带看" />
            <el-option label="商谈合同要素" value="商谈合同要素" />
            <el-option label="定金缴纳" value="定金缴纳" />
          </el-select>
        </el-form-item>

        <!-- 跟进时间 -->
        <el-form-item label="跟进时间" prop="followUpTime">
          <!-- 日期选择器，默认当天 -->
          <el-date-picker
            v-model="formDataAddFollow.followUpDate"
            type="date"
            placeholder="选择日期"
            :disabled-date="followDateOptions1.disabledDate1"
            style="width: 48%"
            @change="handleDateChange"
          />
          <!-- 时间选择器，可选择时分秒 -->
          <el-time-picker
            v-model="formDataAddFollow.followUpTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            style="width: 48%; margin-left: 4%"
          />
        </el-form-item>
        <!-- 跟进记录 -->
        <el-form-item label="跟进记录" prop="followUpContent">
          <el-input
            v-model="formDataAddFollow.followUpContent"
            type="textarea"
            :rows="4"
            placeholder="请填写跟进过程及结果，不少于10个字"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 修改下次跟进时间的表单项 -->
        <el-form-item label="下次跟进时间">
           <el-date-picker
            v-model="formDataAddFollow.replyTime"
            type="date"
            placeholder="请选择下次跟进时间"
            :disabled-date="followDateOptions.disabledDate"
            style="width: 48%"
          />
        </el-form-item>

          <!-- 修改上传图片控件部分 -->
          <el-form-item label="请上传打卡图片" prop="attachmentUrl">
            <div style="display: flex; align-items: center;">
              <el-upload
                :action="uploadUrl"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :http-request="handleUploadRequest"
                name="file"
                :show-file-list="false"
                :headers="headers"
                v-if="type == 'url'"
              >
                <!-- 根据是否有图片显示不同按钮 -->   
                <el-button 
                  v-if="!formDataAddFollow.attachmentUrl" 
                  size="large" 
                  icon="Plus" 
                  style="font-size: 35px;"
                ></el-button>
              </el-upload>
              
              <!-- 图片回显显示和删除按钮 -->
              <div v-if="formDataAddFollow.attachmentUrl" style="position: relative; margin-left: 10px;">
                <img 
                  :src="formDataAddFollow.attachmentUrl" 
                  alt="上传的图片" 
                  style="max-width: 200px; max-height: 200px; border: 1px solid #ddd; border-radius: 4px;"
                />
                <el-button 
                  size="small" 
                  type="danger" 
                  icon="Delete" 
                  @click.stop="handleDeleteImage"
                  style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0, 0, 0, 0.3); border: none; padding: 5px;"
                ></el-button>
              </div>
            </div>
          </el-form-item>
      
      
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseFollowUp">关闭</el-button>
          <el-button type="primary" @click="handleSubmitFollowUp">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增联系人弹窗 -->
    <el-dialog
      v-model="addContactDialogVisible"
      title="新增联系人"
      width="600px"
      :before-close="handleAddContactClose"
    >
      <el-form
        ref="addContactFormRef"
        :model="addContactForm"
        :rules="addContactRules"
        label-width="120px"
        class="info-form"
      >
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="addContactForm.companyName" disabled />
        </el-form-item>

        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="addContactForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>

        <el-form-item label="职务/头衔" prop="position">
          <el-input v-model="addContactForm.position" placeholder="请输入职务/头衔" />
        </el-form-item>

        <el-form-item label="联系人手机" prop="mobile">
          <el-input v-model="addContactForm.mobile" placeholder="请输入联系人手机" />
        </el-form-item>

        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="addContactForm.wechat" placeholder="请输入微信号" />
        </el-form-item>

        <el-form-item label="联系人籍贯" prop="nativeProvince">
          <div class="address-select">
            <el-input
              v-model="addContactForm.nativeProvince"
              placeholder="所在省或直辖市名"
              style="width: 180px; margin-right: 10px"
            />
            <el-input
              v-model="addContactForm.nativeCity"
              placeholder="所在市"
              style="width: 180px; margin-right: 10px"
            />
            <el-input
              v-model="addContactForm.nativeDistrict"
              placeholder="所在区/县"
              style="width: 180px"
            />
          </div>
        </el-form-item>

        <el-form-item label="公司角色" prop="role">
          <el-select
            v-model="addContactForm.role"
            placeholder="请选择公司角色"
            style="width: 100%"
          >
            <el-option label="法人" value="法人" />
            <el-option label="主办会计" value="主办会计" />
            <el-option label="主要负责人" value="主要负责人" />
            <el-option label="日常联系人" value="日常联系人" />
            <el-option label="租住使用人" value="租住使用人" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系人性别" prop="gender">
          <el-select
            v-model="addContactForm.gender"
            placeholder="请选择性别"
            style="width: 100%"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系人学历" prop="education">
          <el-select
            v-model="addContactForm.education"
            placeholder="请选择学历"
            style="width: 100%"
          >
            <el-option label="高中及以下" value="高中及以下" />
            <el-option label="大专" value="大专" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
          </el-select>
        </el-form-item>

        <el-form-item label="毕业院校及专业" prop="graduateSchool">
          <el-input
            v-model="addContactForm.graduateSchool"
            placeholder="请输入毕业院校及专业"
          />
        </el-form-item>

        <el-form-item label="联系人年龄" prop="age">
          <el-input
            v-model="addContactForm.age"
            placeholder="具体年龄或者年龄范围 (30-35,35-40, ...)"
          />
        </el-form-item>

        <el-form-item label="联系人生日" prop="birthday">
          <el-date-picker
            v-model="addContactForm.birthday"
            type="date"
            placeholder="选择联系人生日"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="亲密程度" prop="intimacyLevel">
          <el-select
            v-model="addContactForm.intimacyLevel"
            placeholder="请选择亲密程度"
            style="width: 100%"
          >
            <el-option label="初相识" value="初相识" />
            <el-option label="一般关系" value="一般关系" />
            <el-option label="朋友关系" value="朋友关系" />
            <el-option label="好友关系" value="好友关系" />
          </el-select>
        </el-form-item>

        <el-form-item label="个人爱好" prop="personalHobby">
          <el-input v-model="addContactForm.personalHobby" placeholder="请输入个人爱好" />
        </el-form-item>

        <el-form-item label="其他备注" prop="remark">
          <el-input
            v-model="addContactForm.remark"
            placeholder="请输入其他备注"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddContactClose">取消</el-button>
          <el-button type="primary" @click="submitAddContactForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getFollowRecodeList,
  getDepartmentList,
  getDepartmentAllList,
  getResponsiblePersonList,
  getResponsiblePersonAllList,
  addRecode,
  getById,
  addFollowRecord,
  getByCustomerCode,
  getUserProjectList,
  getContactListByCustomerCode,
  getAccompanyingVisitorList,
  getAccompanyingVisitorListAll
} from "@/api/AttractInvestment/follow/index.js";
import CompanyDetailDrawer from "./CompanyDetailDrawer.vue"; // 引入抽屉组件
import useUserStore from "@/store/modules/user";
import { contacetInsert } from "@/api/AttractInvestment/customer/index.js";
// 图片上传↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 在 script setup 部分添加必要的导入
import { getCurrentInstance } from 'vue'
import { get } from "@vueuse/core";
// 获取当前实例以访问 proxy
const { proxy } = getCurrentInstance()
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_ZS_API + "/AttractInvestment/follow/submit"); // 上传的图片服务器地址
// 添加 type 变量定义
const type = ref('url');
// 添加 headers 变量定义（如果需要认证）
const headers = ref({
  // Authorization: 'Bearer your-token' // 根据实际需要添加
});
// 声明 props（如果需要 fileSize 属性）
const props = defineProps({
  fileSize: {
    type: Number,
    default: 20 // 默认文件大小限制为 2MB
  }
})
// 修改 handleBeforeUpload 函数
function handleBeforeUpload(file) {
  const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
  const isJPG = type.includes(file.type);
  // 检验文件格式
  if (!isJPG) {
    proxy.$modal.msgWarning(`图片格式错误!`);
    return false;
  }
  // 校检文件大小（固定为 2MB 限制）
  const maxSize = 20;
  const isLt = file.size / 1024 / 1024 < maxSize;
  if (!isLt) {
    proxy.$modal.msgWarning(`上传文件大小不能超过 ${maxSize} MB!`);
    return false;
  }
  return true;
}

// 修改 handleUploadSuccess 函数
function handleUploadSuccess(res, file) {
  // 如果上传成功
  if (res.code == 200) {
    ElMessage.success("图片上传成功");
    if (res.msg) {
      formDataAddFollow.attachmentUrl = res.msg; // 假设返回的URL在res.data中
    }
    // 如果需要在其他地方使用上传的图片，可以在这里处理
  } else {
    proxy.$modal.msgError("图片上传失败");
  }
}

// 添加一个新的上传处理函数，使用 fetch 方式
async function handleUploadRequest(option) {
  const { file, onSuccess, onError } = option;
  
  const formData = new FormData();
  formData.append('file', file);
  
  try {
    const response = await fetch(import.meta.env.VITE_APP_BASE_ZS_API + "/AttractInvestment/follow/submit", {
      method: 'POST',
      body: formData
    });
    
    const result = await response.json();
    
    if (response.ok && result) {
      onSuccess(result, file);
    } else {
      onError(new Error(result.message || '上传失败'));
    }
  } catch (error) {
    onError(error);
  }
}
// 在 script setup 部分添加删除图片函数
function handleDeleteImage() {
  ElMessageBox.confirm('确定要删除这张图片吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除图片URL
    const imageUrl=formDataAddFollow.attachmentUrl;
    formDataAddFollow.attachmentUrl = "";
    ElMessage.success('图片删除成功');
    handleDeleteImageToOss(imageUrl);
  }).catch(() => {
    // 用户取消删除
  });
}
// 在 script setup 部分添加删除云上图片的函数
function handleDeleteImageToOss(imageUrl) {
  // 调用后端接口删除云上的图片
  // 这里需要你根据实际的API来实现
  fetch(import.meta.env.VITE_APP_BASE_ZS_API + "/AttractInvestment/follow/deleteImage", {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      imageUrl: imageUrl
    })
  })
  .then(response => response.json())
  .then(res => {
    if (res.code == 200) {
      // ElMessage.success('COS云图片已删除');
    } else {
      ElMessage.error('COS云图片删除失败: ' + (res.msg || '未知错误'));
    }
  })
  .catch(error => {
    console.error('删除COS云图片出错:', error);
    ElMessage.error('COS云图片删除失败');
  });
}
// 上传失败处理
function handleUploadError() {
  proxy.$modal.msgError("图片插入失败");
}
// 图片上传↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

const userStr = useUserStore();
const { username, nickname, gszt, deptId, deptName } = userStr;

// 路由
const router = useRouter();
// 添加日期格式化函数
const formatDateTime = (dateString) => {
  if (!dateString) return "";
  return dateString.replace("T", " ");
};

// 客户类型选项
const customerTypeOptions = reactive([
  {
        label: '企业客户',
        value: '企业客户'
    },
    {
        label: '招商渠道',
        value: '招商渠道',
        children: [
            { label: '政府部门', value: '政府部门' },
            { label: '商会协会', value: '商会协会' },
            { label: '同行载体', value: '同行载体' },
            { label: '中介服务', value: '中介服务' },
            { label: '财税服务', value: '财税服务' },
            { label: '法律服务', value: '法律服务' }
        ]
    }
]);
const cascaderProps = {
  checkStrictly: true,
  expandTrigger: "hover",
  multiple: true,
};

// 处理客户类型变化
const handleCustomerTypeChange = () => {
  // 客户类型变化时会自动通过processCustomerTypeFilter处理
};

// 查询参数
const queryParams = reactive({
  startTime: "",
  endTime: "",
  companyName: "",
  dateRange: [],
  department: [],
  investmentStaff: [],
  followMethod: "",
  investmentTarget: [],
  category: [],
  investmentTargetValue: [],
  accompanyStaff: [],
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const tableData = ref([]);
// 分页信息
const total = ref(0);
// 加载状态
const loading = ref(false);

// 抽屉相关
const drawerVisible = ref(false);
const selectedRow = ref(null); // 存储当前选中的行数据
//联系人
const AddFollowContactList = ref([]); // 用于存储联系人列表

//动态搜索部门招商员列表↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓-------
// 在 existing code 中添加以下内容
const departmentLoading = ref(false);
const filteredDepartmentList = ref([]);
// 初始化时设置过滤列表
onMounted(() => {
  filteredDepartmentList.value = departmentAllList.value;
});
// 过滤列表
const filterDepartments = (query) => {
  departmentLoading.value = true;
  if (query) {
    filteredDepartmentList.value = departmentAllList.value.filter(item => 
      item.toLowerCase().includes(query.toLowerCase())
    );
  } else {
    filteredDepartmentList.value = departmentAllList.value;
  }
  departmentLoading.value = false;
};
//---------------------------------------------------------
const investmentStaffLoading = ref(false);
const filteredInvestmentStaffList = ref([]);
// 初始化时设置过滤列表
onMounted(() => {
  filteredInvestmentStaffList.value = responsiblePersonAllList.value;
});
// 过滤列表
const filterInvestmentStaffs = (query) => {
  investmentStaffLoading.value = true;
  if (query) {
    filteredInvestmentStaffList.value = responsiblePersonAllList.value.filter(item => 
      item.toLowerCase().includes(query.toLowerCase())
    );
  } else {
    filteredInvestmentStaffList.value = responsiblePersonAllList.value;
  }
  investmentStaffLoading.value = false;
};
//动态搜索部门招商员列表↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑--------

//新增跟进记录,查询项目列表↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//动态搜索陪访人员列表↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 在 existing code 中添加以下内容
const accompanyingVisitorLoading = ref(false);
const filteredAccompanyingVisitorList = ref([]);
// 初始化时设置过滤列表
onMounted(() => {
  filteredAccompanyingVisitorList.value = accompanyingVisitorList.value;
});
// 过滤陪访人员列表
const filterAccompanyingVisitors = (query) => {
  accompanyingVisitorLoading.value = true;
  if (query) {
    filteredAccompanyingVisitorList.value = accompanyingVisitorList.value.filter(item => 
      item.toLowerCase().includes(query.toLowerCase())
    );
  } else {
    filteredAccompanyingVisitorList.value = accompanyingVisitorList.value;
  }
  accompanyingVisitorLoading.value = false;
};
//动态搜索陪访人员列表↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑


// 添加项目列表数据
const projectList = ref([]);
// 获取用户项目列表
const fetchUserProjectList = async () => {
  try {
    const params = {
      username: username,
      nickname: nickname,
    };
    const res = await getUserProjectList(params);
    if (res && res.code === 200) {
      projectList.value = res.data || [];
    } else {
      projectList.value = [];
    }
  } catch (error) {
    console.error("获取用户项目列表失败:", error);
    projectList.value = [];
  }
};
//新增跟进记录,查询项目列表↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//查询陪访人员listname↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 陪访人员列表
const accompanyingVisitorList = ref([]);

// 获取陪访人员列表
const fetchAccompanyingVisitorList = async () => {
  try {
    const params = {
      username: username,
      nickname: nickname,
    };
    const res = await getAccompanyingVisitorListAll(params);
    if (res && res.code === 200) {
      accompanyingVisitorList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      accompanyingVisitorList.value = [];
    }
  } catch (error) {
    console.error("获取陪访人员列表失败:", error);
    accompanyingVisitorList.value = [];
  }
};
//查询陪访人员listname↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//新增跟进记录↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 新增联系人表单验证规则 
const addFollowRecodeRules = reactive({
  contactPerson: [{ required: true, message: "请选择联系人姓名",trigger: "blur" }],
  followUpType: [
    { required: true, message: '请选择跟进方式', trigger: 'change' }
  ],
   customerIntentionLevel: [
    { required: true, message: '请选择客户意向等级', trigger: 'change' }
  ],
  investmentTarget: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  customerProgress: [
    { required: true, message: '请选择招商阶段', trigger: 'change' }
  ],
  followUpTime: [
    { required: true, message: '请选择跟进时间', trigger: 'change' }
  ],
  followUpContent: [
    { required: true, message: '请填写跟进记录', trigger: 'blur' },
    { min: 10, message: '跟进记录不能少于10个字', trigger: 'blur' }
  ],
    attachmentUrl: [ 
    { required: true, message: '请上传打卡图片', trigger: 'blur' }
  ]
});
const dialogAddFollowUpVisible = ref(false);
// 日期选项 - 只能选择当天及以后（根据需求调整）
const followDateOptions = reactive({
  disabledDate: (time) => {
    // 如果只能选择当天，使用这个：
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return time.getTime() < today.getTime();
    
    // 如果可以选择当天及以后，使用这个：
    // const today = new Date();
    // today.setHours(0, 0, 0, 0);
    // return time.getTime() < today.getTime();
  },
});
const followDateOptions1 = reactive({
  disabledDate1: (time) => {
    // 如果只能选择当天，使用这个：
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return time.getTime() > today.getTime();
    
    // 如果可以选择当天及以后，使用这个：
    // const today = new Date();
    // today.setHours(0, 0, 0, 0);
    // return time.getTime() < today.getTime();
  },
});
// 处理日期变化
const handleDateChange = (date) => {
  // 如果需要，可以在这里处理日期变化逻辑
  console.log("选择的日期:", date);
};

// 修改 formDataAddFollow 数据结构
/**
 * company_name
accompany_staff
招商对象企业 investment_target
contact_person
follow_up_type
客户意向等级 customer_intention_level
招商对象 customer_source
招商阶段customer_progress
跟进时间follow_up_time
跟进记录follow_up_content
下次跟进时间 auto_create_time */
const formDataAddFollow = reactive({
  companyName: "",
  accompanyStaff: "",
  investmentTarget: "",
  contactPerson: "",
  followUpType: "",
  customerIntentionLevel: "",
  // customerSource: "",
  customerProgress: "",
  //   followUpTime: new Date().toLocaleDateString(),
  followUpContent: "",
  replyTime: "",
  //创建人creator_name 项目名department 招商员investment_staff  商户编号customer_code
  creatorName: "",
  department: "",
  investmentStaff: "",
  customerCode: "",
  attachmentUrl: "" ,// 添加图片URL字段
  followUpDate: new Date(), // 新增日期字段，默认当天
  followUpDate1: new Date(), // 新增日期字段，默认当天
  followUpTime: "" // 时间字段
});
const selectedProjects = ref(null); // 用于存储当前选中的项目信息

// 修改 handleProjectChange 函数
const handleProjectChange = async (selectedCompanyName) => {
  // 根据选中的公司名称找到对应的项目
  const selectedProject = projectList.value.find(
    (project) => project.companyName === selectedCompanyName
  );

  // 保存选中的项目信息
  selectedProjects.value = selectedProject;

  // 设置 customerCode
  if (selectedProject) {
    formDataAddFollow.customerCode = selectedProject.customerId || "";
    // 使用 customerCode 查询联系人列表
    await fetchContactList(selectedProject.customerId);
  } else {
    formDataAddFollow.customerCode = "";
    AddFollowContactList.value = [];
  }
};
// 添加获取联系人列表的函数
const fetchContactList = async (customerCode) => {
  try {
    if (!customerCode) {
      AddFollowContactList.value = [];
      return;
    }

    const res = await getContactListByCustomerCode(customerCode);
    if (res && res.code === 200) {
      // 假设后端返回的数据结构为 { code: 200, data: ['联系人1', '联系人2', ...] }
      AddFollowContactList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      AddFollowContactList.value = [];
    }
  } catch (error) {
    console.error("获取联系人列表失败:", error);
    AddFollowContactList.value = [];
  }
};
// 修改 handleAddFollowUp 函数
function handleAddFollowUp() {
  // 清空表单数据
  Object.assign(formDataAddFollow, {
    companyName: "",
    accompanyStaff: "",
    investmentTarget: "",
    contactPerson: "",
    followUpType: "",
    customerIntentionLevel: "",
    customerSource: "",
    customerProgress: "",
    followUpContent: "",
    replyTime: "",
    creatorName: "",
    department: "",
    investmentStaff: "",
    customerCode: "",
    followUpDate: new Date(), // 默认当天
    followUpTime: "" // 清空时间
  });

  // 先获取项目列表
  fetchUserProjectList().then(() => {
    formDataAddFollow.creatorName = username || "";
    formDataAddFollow.department = deptName || "";
    formDataAddFollow.investmentStaff = nickname || "";
    dialogAddFollowUpVisible.value = true;
    fetchAccompanyingVisitorList();
  });
}
// 表单引用
const formRefFollowUp = ref(null);
// 提交表单
// 修改提交函数中的时间处理
function handleSubmitFollowUp() {
  formRefFollowUp.value.validate((valid) => {
    if (valid) {
      // 处理 accompanyStaff 数据，如果是数组则转换为字符串
      let accompanyStaffValue = formDataAddFollow.accompanyStaff;
      if (Array.isArray(accompanyStaffValue)) {
        accompanyStaffValue = accompanyStaffValue.join(",");
      }

      // 组合日期和时间
      let combinedDateTime = "";
      if (formDataAddFollow.followUpDate) {
        const datePart = new Date(formDataAddFollow.followUpDate);
        const year = datePart.getFullYear();
        const month = String(datePart.getMonth() + 1).padStart(2, "0");
        const day = String(datePart.getDate()).padStart(2, "0");
        
        // 如果有选择时间，使用选择的时间，否则使用当前时间
        const timePart = formDataAddFollow.followUpTime || 
          new Date().toTimeString().slice(0, 8);
        
        combinedDateTime = `${year}-${month}-${day} ${timePart}`;
      } else {
        // 如果没有选择日期，使用当前日期和时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, "0");
        const day = String(now.getDate()).padStart(2, "0");
        const timePart = formDataAddFollow.followUpTime || 
          now.toTimeString().slice(0, 8);
        
        combinedDateTime = `${year}-${month}-${day} ${timePart}`;
      }

      // 创建提交数据
      const submitData = {
        ...formDataAddFollow,
        accompanyStaff: accompanyStaffValue,
        followUpTime: combinedDateTime,
      };

      // 移除不需要提交的临时字段
      delete submitData.followUpDate;

      // 调用 API 创建渠道
      console.log("提交数据:", submitData);
      addFollowRecord(submitData)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("新增成功");
            dialogAddFollowUpVisible.value = false;
            // 刷新列表
            fetchData();
          } else {
            proxy.$modal.msgError(res.msg || "新增失败");
          }
        })
        .catch((error) => {
          console.error("新增渠道失败:", error);
        });
    }
  });
}
// 限制只能选择当前时间之前的时间（包括今天）

// 在组件挂载时检查配置
const pickerOptions = reactive({
  disabledDate: (time) => {
    console.log("disabledDate 被调用", time);
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    return time.getTime() < today.getTime() || time.getTime() >= tomorrow.getTime();
  },
});
// 关闭弹窗
function handleCloseFollowUp() {
  dialogAddFollowUpVisible.value = false;
  formDataAddFollow.attachmentUrl = "";
}

//新增跟进记录↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//新增联系人↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 新增联系人弹窗状态
const addContactDialogVisible = ref(false);
// 新增联系人表单数据
const addContactForm = reactive({
  customerId: "",
  companyName: "",
  contactName: "",
  position: "",
  mobile: "",
  wechat: "",
  nativeProvince: "",
  nativeCity: "",
  nativeDistrict: "",
  role: "",
  gender: "",
  education: "",
  graduateSchool: "",
  age: "",
  birthday: "",
  intimacyLevel: "",
  personalHobby: "",
  remark: "",
});

// 新增联系人表单验证规则
const addContactRules = reactive({
  contactName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
  nativeProvince: [{ required: true, message: "请输入联系人籍贯省份", trigger: "blur" }],
});

// 新增联系人表单引用
const addContactFormRef = ref(null);

// 打开新增联系人弹窗
const openAddContactForm = () => {
  // 检查是否已选择目标客户
  if (!selectedProjects.value) {
    ElMessage.warning("请先选择目标客户");
    return;
  }
  // 重置表单
  resetAddContactForm();
  // 设置公司名称
  addContactForm.companyName = selectedProjects.value.companyName;
  addContactForm.customerId = selectedProjects.value.customerId;
  addContactDialogVisible.value = true;
};

// 关闭新增联系人弹窗
const handleAddContactClose = () => {
  ElMessageBox.confirm("确认放弃修改吗？")
    .then(() => {
      addContactDialogVisible.value = false;
      resetAddContactForm();
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 重置新增联系人表单
function resetAddContactForm() {
  addContactFormRef.value?.resetFields();
  for (let key in addContactForm) {
    if (typeof addContactForm[key] === "string") {
      addContactForm[key] = "";
    } else if (Array.isArray(addContactForm[key])) {
      addContactForm[key] = [];
    } else if (typeof addContactForm[key] === "object" && addContactForm[key] !== null) {
      addContactForm[key] = {};
    }
  }
}

// 提交新增联系人表单
function submitAddContactForm() {
  addContactFormRef.value.validate((valid) => {
    if (valid) {
      const submitData = { ...addContactForm };

      // 调用API提交联系人信息
      contacetInsert(submitData)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("联系人添加成功");
            addContactDialogVisible.value = false;
            resetAddContactForm();
            // 重新查询联系人列表
            if (formDataAddFollow.customerCode) {
              fetchContactList(formDataAddFollow.customerCode);
            }
          } else {
            ElMessage.error(res.msg || "添加失败");
          }
        })
        .catch((err) => {
          console.error("添加联系人失败:", err);
          ElMessage.error("添加联系人失败");
        });
    } else {
      ElMessage.error("请检查输入内容");
    }
  });
}
//新增联系人↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
// 当前公司数据
const currentCompany = reactive({
  department: "",
  companyName: "",
  estimatedTax: "",
  reportTime: "",
  estimatedAchievementTime: "",
  businessDeveloper: "",
  id: "",
  customerId: "",
});

// 获取企业详情（模拟接口）
const fetchCompanyDetail = async (row) => {
  try {
    const res = await getById(row);
    if (res && res.code === 200) {
      return res.data;
    }
  } catch (error) {
    console.error("获取企业详情失败:", error);
  }
  return null;
};

// 查看企业详情（打开抽屉）
const handleViewFollow = (row) => {
  viewCompanyDetail(row);
};

const viewCompanyDetail = async (row) => {
  selectedRow.value = row;
  const detail = await fetchCompanyDetail(row);
  console.info("------查看企业详情（打开抽屉）-----------", detail);
  if (detail) {
    selectedRow.value = detail;
    drawerVisible.value = true;
  }
};
// 格式化本地日期函数
function formatLocalDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
// 获取数据
const fetchData = async () => {
  fetchAccompanyingVisitorList();
  loading.value = true;
  try {
     // 处理时间范围
    if (queryParams.dateRange && queryParams.dateRange.length === 2) {
      const [startDate, endDate] = queryParams.dateRange;
      console.info("------startDate-----------", startDate);
      console.info("------endDate-----------", endDate);
      
      // 使用本地时间格式化，避免时区问题
      const startTime = formatLocalDate(startDate);
      const endTime = formatLocalDate(endDate);
      
      queryParams.startTime = startTime;
      queryParams.endTime = endTime;
  } else {
      delete queryParams.startTime;
      delete queryParams.endTime;
  }
  console.info("------queryParams-----------", queryParams);
    const res = await getFollowRecodeList(queryParams);
    if (res && res.code == 200 && res.data) {
      const pageData = res.data;
      // 防御性处理，确保rows为数组
      let rows = [];
      if (Array.isArray(pageData.rows)) {
        rows = pageData.records;
      } else if (
        pageData.records &&
        typeof pageData.records === "object" &&
        typeof pageData.records.length === "number"
      ) {
        rows = Array.from(pageData.records);
      }
      tableData.value = rows;
      total.value = pageData.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取企业列表失败:", error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};
// 部门列表
const departmentList = ref([]);
const departmentAllList = ref([]);

// 获取部门列表数据
const fetchDepartmentList = async () => {
  console.info("------start-----------");

  loading.value = true;
  try {
    const res = await getDepartmentList();
    console.info("------获取部门列表数据-----------", res.data);
    // 验证响应结构
    if (!res || res.code !== 200) {
      console.warn("获取部门列表：响应格式不正确", res);
      departmentList.value = [];
      return;
    }

    // 处理部门列表数据，确保为数组
    if (Array.isArray(res.data)) {
      departmentList.value = res.data;
    } else if (
      res.data &&
      typeof res.data === "object" &&
      typeof res.data.length === "number"
    ) {
      // 处理类数组对象
      departmentList.value = Array.from(res.data);
    } else {
      console.warn("获取部门列表：数据格式不正确，期望数组类型", res.data);
      departmentList.value = [];
    }
  } catch (error) {
    console.error("获取部门列表失败:", error);
    departmentList.value = [];
  } finally {
    loading.value = false;
  }
};
const fetchDepartmentAllList = async () => {
  console.info("------start-----------");

  loading.value = true;
  try {
    const res = await getDepartmentAllList();
    console.info("------获取部门列表数据-----------", res.data);
    // 验证响应结构
    if (!res || res.code !== 200) {
      console.warn("获取部门列表：响应格式不正确", res);
      departmentAllList.value = [];
      return;
    }

    // 处理部门列表数据，确保为数组
    let rawData = [];
    if (Array.isArray(res.data)) {
      rawData = res.data;
    } else if (
      res.data &&
      typeof res.data === "object" &&
      typeof res.data.length === "number"
    ) {
      // 处理类数组对象
      rawData = Array.from(res.data);
    } else {
      console.warn("获取部门列表：数据格式不正确，期望数组类型", res.data);
      departmentAllList.value = [];
      return;
    }
    
    // 过滤掉空字符串和"undefined"字符串
    departmentAllList.value = rawData.filter(item => 
      item !== "" && item !== "undefined" && item != null
    );
  } catch (error) {
    console.error("获取部门列表失败:", error);
    departmentAllList.value = [];
  } finally {
    loading.value = false;
  }
};
// 招商员列表
const responsiblePersonList = ref([]);
const responsiblePersonAllList = ref([]);
// 获取招商员列表数据
const fetchResponsiblePersonList = async () => {
  loading.value = true;
  try {
    // 传递部门参数给后端API进行筛选
    console.info("------start-----------" + queryParams);
    const res = await getResponsiblePersonList(queryParams);

    console.info("------获取招商员列表数据-----------", res.data);

    // 验证响应结构
    if (!res || res.code !== 200) {
      console.warn("获取招商员列表：响应格式不正确", res);
      responsiblePersonList.value = [];
      return;
    }

    // 处理招商员列表数据，确保为数组
    if (Array.isArray(res.data)) {
      responsiblePersonList.value = res.data;
    } else if (
      res.data &&
      typeof res.data === "object" &&
      typeof res.data.length === "number"
    ) {
      // 处理类数组对象
      responsiblePersonList.value = Array.from(res.data);
    } else {
      console.warn("获取招商员列表：数据格式不正确，期望数组类型", res.data);
      responsiblePersonList.value = [];
    }
  } catch (error) {
    console.error("获取招商员列表失败:", error);
    responsiblePersonList.value = [];
  } finally {
    loading.value = false;
  }
};
const fetchResponsiblePersonAllList = async () => {
  loading.value = true;
  try {
    // 传递部门参数给后端API进行筛选
    console.info("------start-----------" + queryParams);
    const res = await getResponsiblePersonAllList();

    console.info("------获取招商员列表数据-----------", res.data);

    // 验证响应结构
    if (!res || res.code !== 200) {
      console.warn("获取招商员列表：响应格式不正确", res);
      responsiblePersonAllList.value = [];
      return;
    }

    // 处理招商员列表数据，确保为数组
    if (Array.isArray(res.data)) {
      responsiblePersonAllList.value = res.data;
    } else if (
      res.data &&
      typeof res.data === "object" &&
      typeof res.data.length === "number"
    ) {
      // 处理类数组对象
      responsiblePersonAllList.value = Array.from(res.data);
    } else {
      console.warn("获取招商员列表：数据格式不正确，期望数组类型", res.data);
      responsiblePersonAllList.value = [];
    }
  } catch (error) {
    console.error("获取招商员列表失败:", error);
    responsiblePersonAllList.value = [];
  } finally {
    loading.value = false;
  }
};
// 监听部门选择变化，自动查询招商员
watch(
  () => queryParams.department,
  (newDepartment) => {
    if (newDepartment) {
      // fetchResponsiblePersonList(newDepartment);
    } else {
      // 如果部门被清空，清空招商员列表
      // responsiblePersonList.value = [];
    }
  }
);
// 处理客户类型筛选条件
const processCustomerTypeFilter = () => {
  // 重置投资目标和分类
  queryParams.investmentTarget = [];
  queryParams.category = [];

  if (!queryParams.investmentTargetValue || !Array.isArray(queryParams.investmentTargetValue)) {
    return;
  }

  // 遍历选中的值，分离一级选项和二级选项
  queryParams.investmentTargetValue.forEach(item => {
    // 检查是否为数组，数组表示选择了子选项
    if (Array.isArray(item)) {
      if (item.length === 2) {
        // 如果还没有添加一级选项，则添加
        if (!queryParams.investmentTarget.includes(item[0])) {
          queryParams.investmentTarget.push(item[0]);
        }
        // 添加二级选项
        queryParams.category.push(item[1]);
      }
    } else {
      // 直接选择了一级选项
      queryParams.investmentTarget.push(item);
    }
  });
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  processCustomerTypeFilter();
  fetchData();
};

// 重置表单
const resetForm = () => {
  // 重置查询参数
  Object.assign(queryParams, {
    companyName: "",
    dateRange: [],
    department: [],
    investmentStaff: [],
    responsiblePerson: "",
    followMethod: "",
    investmentTarget: [],
    category: [],
    investmentTargetValue: [],
    accompanyStaff: [],
    pageNum: 1,
    pageSize: 10,
  });
  fetchData();
};

// 添加获取跟进方式标签类型的方法
const getFollowUpTypeTagType = (type) => {
  switch (type) {
    case '上门拜访':
      return 'success'; // 绿色
    case '来访接待':
      return 'primary'; // 蓝色
    case '电话拜访':
      return 'info'; // 青色/灰色
    case 'QQ微信联系':
      return 'info'; // 灰色
    default:
      return '';
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
  // fetchDepartmentList();
  fetchDepartmentAllList();
  fetchResponsiblePersonAllList();
});
</script>

<style scoped>
.record-container {
  padding: 20px;
}

.searchBox {
  margin-bottom: 20px;
}

.tableContainer {
  margin-bottom: 20px;
}
.info-form {
    margin-top: 0;
}
.follow-type-green {
  color: #67c23a;
  background-color: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.follow-type-blue {
  color: #409eff;
  background-color: #ecf5ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.follow-type-cyan {
  color: #40c0c0;
  background-color: #e6f7ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.follow-type-gray {
  color: #909399;
  background-color: #f4f4f5;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>
